package com.itheima.service;

import com.itheima.dao.UserAuthorityMapper;
import com.itheima.dao.UserAuthorityRelationMapper;
import com.itheima.dao.UserMapper;
import com.itheima.model.domain.User;
import com.itheima.model.domain.UserAuthority;
import com.itheima.model.domain.UserAuthorityRelation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Date;
import java.util.List;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserAuthorityMapper userAuthorityMapper;
    @Autowired
    UserAuthorityRelationMapper userAuthorityRelationMapper;

    public List<User> findAll(){
        return userMapper.findAll();
    }
    @Transactional
    public Integer insert(User user){
        //加密 原始密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encrypass = encoder.encode(user.getPassword());
        user.setPassword(encrypass);
        //创建日期
        user.setCreated(new Date(System.currentTimeMillis()));
        //新用户初值设置为1，代表有效
        user.setValid(1);

        Integer ret = userMapper.insert(user);
        Integer userid = userMapper.getMaxId();

        //由于SpringSecurity JDBC验证方式需要检查角色表（t_authority）和权限对应表(t_user_authority)，需要单独设置

        //UserAuthority userAuthority = new UserAuthority();

        //新用户缺省为COMMON，ID值为 2

        // /userAuthority.setId(2);
        //userAuthority.setAuthority("ROLE_COMMON");
        //userAuthorityMapper.insert(userAuthority);

        UserAuthorityRelation userAuthorityRelation = new UserAuthorityRelation();
        userAuthorityRelation.setUser_id(userid);
        userAuthorityRelation.setAuthority_id(2);
        userAuthorityRelationMapper.insert(userAuthorityRelation);

        return ret;
    }
}
